<template>
	<view class="page" style="padding-bottom: 180rpx">
		<view class="scan-box">
			<view class="scan-t">
				今日累计打卡
			</view>
			<view class="scan-c">
				{{ clockCount }}
			</view>

			<view class="scan-b" @click="scanFn">
				<u-icon name="scan" color="#fff" size="92"></u-icon>
				<text class="txt">扫码打卡</text>
			</view>

			<view class="scan-code" v-if="scanSuccess">
				<u-icon name="map-fill" color="#D1D1D1" size="46"></u-icon>
				<view class="txt">
					{{ form.qrCode }}
				</view>
			</view>
			<!--<view class="" v-if="scanSuccess" style="margin-top: 20rpx;color: #999">-->
			<!--  距离打卡点{{ distance }}米-->
			<!--  <p v-if="distance>20" style="color: red;margin-top: 10rpx">距离过远，无法打卡！</p>-->
			<!--</view>-->
		</view>

		<template v-if="canInsert">
			<view class="xb-info" style="margin-top: 20rpx;">
				<view class="form-col">
					<text>巡逻人</text>
					<input type="text" v-model="form.inspectionPerson" placeholder="请输入" placeholder-class="inputClass"
						disabled="true" />
				</view>

				<view>
					<text>巡更状态</text>
					<radio-group @change="touchChange">
						<label>
							<radio value="正常" :checked="form.state == '正常'"
								style="width: 40rpx;height: 40rpx;margin-right: 14rpx;" />
							<span style="font-size: 30rpx;color: #333">正常</span>
						</label>

						<label>
							<radio value="异常" :checked="form.state == '异常'"
								style="width: 40rpx;height: 40rpx;margin-right: 14rpx;" />
							<span style="font-size: 30rpx;color: #333">异常</span>
						</label>
					</radio-group>
				</view>
			</view>


			<div class="xun-content" v-if="formSource">
				<text class="xun-t">巡更内容</text>
				<Parser :form-content="formSource" ref="parser"></Parser>
			</div>

      <view class="xb-info" style="margin-top: 20rpx;">
        <view class="form-col" style="flex-direction: column;align-items: flex-start">
          <text>备注</text>
          <textarea auto-height maxlength="200" v-model="form.remark" placeholder="请输入最多200个字符…"
                    placeholder-class="inputClass"></textarea>
        </view>

      </view>

			<view class="xb-bottom-btn" @click="btnClickFn">
				提交
			</view>
		</template>

		<postSuccess v-if="showSuccess">
			<view slot="txt" class="suc-btnbox">
				<!--<view @click="navToDetails">查看提交信息</view>-->
				<view @click="clockAway">继续打卡</view>
			</view>
		</postSuccess>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				clockCount: 0, //今日打卡数
				form: {
					qrCode: '', //编码
					state: '', //巡更状态
					latitude: '',
					longitude: '',
					inspectionPerson: '', //巡逻人
					formId: '',
					inspectionTime: '',
					formContent: [], //巡更内容
					remark: '',
					distance: 0
				},
				showSuccess: false,
				distance: 0,
				scanSuccess: false,
				canInsert: false,
				formSource: null,
				userInfo: null
			};
		},
		created() {
			this.userInfo = uni.getStorageSync('userAc').userInfo
			this.form.inspectionPerson = this.userInfo.nickName
			this.getInspectionRecordList()
			// #ifdef H5
			this.getInspectionByQr('A-00001')
			// #endif
		},
		methods: {
			scanFn() {
				uni.scanCode({
					onlyFromCamera: true,
					success: (res) => {
						uni.getSystemInfo({
							success: (res2) => {
								if (!res2.locationEnabled) {
									// #ifdef APP-PLUS
									this.openGps()
									// #endif
									// #ifdef MP-WEIXIN
									this.showToast('当前位置开关未打开，无法打卡！')
									return false
									// #endif
								} else {
									uni.showLoading({
										title: '扫码中'
									});
									this.getInspectionByQr(res.result)
									this.form.qrCode = res.result
								}
							}
						})
					},
					fail: (err) => {
						console.log(err);
					}
				})
			},
			openGps() {
				let system = uni.getSystemInfoSync(); // 获取系统信息
				if (system.platform === 'android') { // 判断平台
					var context = plus.android.importClass("android.content.Context");
					var locationManager = plus.android.importClass("android.location.LocationManager");
					var main = plus.android.runtimeMainActivity();
					var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
					if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
						uni.showModal({
							title: '提示',
							content: '请打开定位服务功能',
							showCancel: false, // 不显示取消按钮
							success() {
								var Intent = plus.android.importClass('android.content.Intent');
								var Settings = plus.android.importClass('android.provider.Settings');
								var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
								main.startActivity(intent); // 打开系统设置GPS服务页面

							}
						});
					}
				} else if (system.platform === 'ios') {
					var cllocationManger = plus.ios.import("CLLocationManager");
					var enable = cllocationManger.locationServicesEnabled();
					var status = cllocationManger.authorizationStatus();
					plus.ios.deleteObject(cllocationManger);
					console.log("手机系统的定位没有打开");
					uni.showModal({
						title: '提示',
						content: '请打开定位服务功能',
						showCancel: false, // 不显示取消按钮
						success() {
							var UIApplication = plus.ios.import("UIApplication");
							var application2 = UIApplication.sharedApplication();
							var NSURL2 = plus.ios.import("NSURL");
							var setting2 = NSURL2.URLWithString("App-Prefs:root=Privacy&path=LOCATION");
							application2.openURL(setting2);
							plus.ios.deleteObject(setting2);
							plus.ios.deleteObject(NSURL2);
							plus.ios.deleteObject(application2);
						}
					});
				}
			},
			touchChange(e) {
				this.form.state = e.detail.value
			},
			async getInspectionByQr(qr) {
				console.log("qr", qr)
				let formSource = []
				// #ifndef H5
				await this.getLocation().then(res => {
					this.form.longitude = res.longitude
					this.form.latitude = res.latitude
				}).catch(err => {
					console.log(err);
				})
				// #endif

				// #ifdef H5
				this.form.longitude = 106.25936
				this.form.latitude = 29.29214
				this.form.qrCode = qr
				// #endif

				await this.apis.securityApi.inspectionByQr(qr).then(res => {
					if (res.code == 200 && res.data) {
						let data = res.data
						let distance = this.getDistance(this.form.latitude, this.form.longitude, data.latitude,
							data.longitude)
						this.form.distance = distance.toFixed(2)
						formSource = JSON.parse(data.formContent)
						formSource.forEach((item, index, arr) => {
							arr[index] = JSON.parse(item)
						})
						this.form.formId = data.formId
						this.formSource = formSource
						this.scanSuccess = true
						this.canInsert = true
						uni.hideLoading()
						//this.canInsert = this.distance <= 20;
					} else {
						uni.hideLoading()
						uni.showToast({
							icon: 'none',
							title: '出现错误，请联系管理员',
							duration: 3000
						})
					}
				})
			},
			getLocation() {
				return new Promise((resolve, rej) => {
					uni.getLocation({
						success: (res) => {
							console.log(1)
							resolve(res)
						},
						fail: (err) => {
							console.log(err)
						}
					})
				})
			},
			getInspectionRecordList() {
				let date = this.$u.timeFormat(Date.now(), 'yyyy-mm-dd')
				this.apis.securityApi.inspectionRecordList({
					inspectionTime: date,
					inspectionPerson: this.form.inspectionPerson,
          recordType:"巡逻"
				}).then(res => {
					let list = res.rows
					this.clockCount = list.length
				})
			},
			clockAway() {
				this.form = {
					qrCode: '', //编码
					state: '', //巡更状态
					latitude: '',
					longitude: '',
					inspectionPerson: this.userInfo.nickName, //巡逻人
					formId: '',
					inspectionTime: '',
					distance: 0,
					formContent: [] //巡更内容
				}
				this.scanSuccess = false
				this.canInsert = false
				this.showSuccess = false
			},
			btnClickFn() {
				let formContent = this.form.formContent = this.$refs.parser.form
				for (let item in formContent) {
					if (this.isEmpty(formContent[item])) {
						this.showToast("请确保巡更内容勾选完整！")
						return false
					}
				}
				this.form.inspectionTime = this.$u.timeFormat(Date.now(), 'yyyy-mm-dd hh:MM:ss')
				if (this.form.state === '') {
					this.showToast('请选择巡更状态!')
					return false
				}
				this.form.recordType="巡逻"
				this.apis.securityApi.inspectionRecord(this.form).then(res => {
					if (res.code == 200) {
						this.showSuccess = true
					}
				})
			},
			/**
			 * @function 通过传入两个经纬度，计算出实际距离（单位：m）
			 * @param {number} lat1  纬度1
			 * @param {number} lng1  经度1
			 * @param {number} lat2  纬度2
			 * @param {number} lng2  经度2
			 * @return {number}
			 *
			 */
			getDistance(lat1, lng1, lat2, lng2) {
				// 地球平均半径
				const EARTH_RADIUS = 6378137;
				// 把经纬度转为度（°）
				// 纬度
				let degree_lat1 = (lat1 * Math.PI) / 180.0;
				let degree_lat2 = (lat2 * Math.PI) / 180.0;
				let a = degree_lat1 - degree_lat2;
				// 经度
				let degree_lng1 = (lng1 * Math.PI) / 180.0;
				let degree_lng2 = (lng2 * Math.PI) / 180.0;
				let b = degree_lng1 - degree_lng2;
				// 距离 （单位：米）
				let s =
					2 *
					Math.asin(
						Math.sqrt(
							Math.pow(Math.sin(a / 2), 2) +
							Math.cos(degree_lat1) *
							Math.cos(degree_lat2) *
							Math.pow(Math.sin(b / 2), 2)
						)
					);
				s = s * EARTH_RADIUS;
				s = Math.round(s * 10000) / 10000;
				return s;
			},
		}
	}
</script>

<style lang="scss">
	.scan-box {
		padding: 40rpx 0;
		width: 100%;
		background: #FFFFFF;
		border-radius: 12px 12px 12px 12px;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;

		.scan-t {
			font-size: 28rpx;
			font-family: PingFang SC-Medium, PingFang SC;
			font-weight: 500;
			color: #666666;
			line-height: 33rpx;
		}

		.scan-c {
			margin: 20rpx 0 30rpx;
			font-size: 60rpx;
			font-family: PingFang SC-Bold, PingFang SC;
			font-weight: bold;
			color: #333333;
			line-height: 70rpx;
		}

		.scan-b {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			width: 246rpx;
			height: 246rpx;
			background: #44D94B;
			border-radius: 50%;
			box-shadow: 0px 0px 40px 2px rgba(68, 217, 75, 0.56);

			.txt {
				margin-top: 16rpx;
				font-size: 28rpx;
				font-family: PingFang SC-Bold, PingFang SC;
				font-weight: bold;
				color: #FFFFFF;
			}
		}

		.scan-code {
			margin-top: 50rpx;
			display: flex;

			.txt {
				margin-left: 20rpx;
				font-size: 50rpx;
				font-family: PingFang SC-Bold, PingFang SC;
				font-weight: bold;
				color: #333333;
				line-height: 70rpx;
			}
		}
	}

	.xun-content {
		padding: 20rpx 36rpx;
		border-radius: 12rpx;
		background: #fff;
	}

	.xun-t {
		padding: 20rpx 0;
		display: block;
		font-size: 28rpx;
		color: #666666;
		font-weight: 600;
		border-bottom: 1px solid #eee;
	}
</style>
